import axios from "axios";
import rest from "../../assets/config/rest";

axios.defaults.timeout = 30000;
axios.defaults.baseURL = rest.host;
axios.defaults.headers["Content-type"] = "application/json";
//http request 拦截器
axios.interceptors.request.use(
  (request) => {
    let method = request.method.toLowerCase();
    if (method === "post" || method === "put") {
      request.data = JSON.stringify(request.data);
    }
    let token = window.localStorage.getItem(rest.token);
    if (!!token) {
      request.headers["Authorization"] = JSON.parse(token).token;
    }
    return Promise.resolve(request);
  },
  (error) => {
    return Promise.reject(error);
  }
);

//http response 拦截器
axios.interceptors.response.use(
  (response) => {
    return Promise.resolve(response);
  },
  (error) => {
    if (error.response.status === 401 || error.response.status === 403) {
      window.location.href = "#/login?error=expired";
    }
    return Promise.reject(error);
  }
);

export default axios;
